package DFS递归搜索与回溯.综合;

import sun.text.resources.cldr.eo.FormatData_eo;

/**
 * @Date 2024/9/14 21:56
 * @description: 单词搜索
 * .https://leetcode.cn/problems/word-search/
 * @Author LittleNight
 */
public class likou79 {

    int[] dx = new int[]{0, 0, 1, -1};
    int[] dy = new int[]{1, -1, 0, 0};
    int m, n;
    boolean[][] vis;
    char[] word;
    public boolean exist(char[][] board, String _word) {
        m = board.length; n = board[0].length;
        word = _word.toCharArray();
        vis = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if(board[i][j] == word[0]) {
                    vis[i][j] = true;
                    if(dfs(board, i, j, 1)) return true;
                    vis[i][j] = false;
                }
            }
        }
        return false;
    }
    private boolean dfs(char[][] board, int i, int j, int pos) {
        if(pos == word.length) {
            // 找到一个答案
            return true;
        }
        // 遍历上下左右四个方向
        for (int k = 0; k < 4; k++) {
            int x = i + dx[k], y = j + dy[k];
            if(x >= 0 && x < m && y >= 0 && y < n && !vis[x][y] && word[pos] == board[x][y]) {
                vis[x][y] = true; // 标记访问过
                if(dfs(board, x, y, pos + 1)) return true;
                vis[x][y] = false; // 回溯: 恢复现场
            }
        }
        // 如果上面for循环没有返回 true. 返回false 标记 i j 这个位置不合适
        return false;
    }

}
